package logmgr;
import java.io.*; 

import Common.ByteArray;
import Transaction.Recovery;


abstract public class LogMgr  {
		public static final int COMMIT = 0 , ROLLBACK = 1  , CHECKPOINT = 2 , START = 3,
		INT = 4, SHORT = 5, CHAR = 6, FLOAT = 7 , STRING = 8 , BYTES = 9 ;
		
		static LogMgr  
			commitIns =  new CommitRecord() ,
			rollbackIns = new RollbackRecord () ,
			startIns = new StartRecord() , 
			intIns = new IntRecord () ,
			stringIns = new StringRecord () ,
			shortIns = new ShortRecord (), 
			floatIns = new FloatRecord (),
			charIns = new CharRecord () ,
			bytesIns = new BytesRecord() ;

		static RandomAccessFile file = Recovery.file;
		
		public int txnum, pageid, pos ;
		
		public static LogMgr getNext () {
			byte [] buff = new byte [ 4 ] ; 
			try {
				if ( file.read( buff )!= 4 ) return null  ;
				int type = ByteArray.readInt ( buff, 0 ) ; 
				switch (type){
				case COMMIT: return new CommitRecord () ;
				case ROLLBACK: return new RollbackRecord() ;
				case START: return new StartRecord() ; 
				case INT: return new IntRecord () ;
				case SHORT: return new ShortRecord () ;
				case CHAR: return new CharRecord () ;
				case FLOAT: return new FloatRecord () ;
				case STRING: return new StringRecord () ;
				case BYTES: return new BytesRecord () ; 
				}
				return null ; 
			}catch ( Exception e ) { 
				return null; 
			}
		}
		
		public static void allWrite ( int type, int txnum, int pageid, int pos, Object old, Object cur) {
			try {
				switch ( type ) {
				case COMMIT: commitIns.write(txnum, pageid, pos, old, cur) ; break ;
				case ROLLBACK: rollbackIns.write(txnum, pageid, pos, old, cur) ; break ;
				case CHECKPOINT: writeCheckpoint () ; break ; 
				case START: startIns.write(txnum, pageid, pos, old, cur) ; break ; 
				case INT: intIns.write(txnum, pageid, pos, old, cur) ; break ; 
				case SHORT: shortIns.write(txnum, pageid, pos, old, cur) ; break ; 
				case CHAR: charIns.write(txnum, pageid, pos, old, cur) ; break ; 
				case FLOAT: floatIns.write(txnum, pageid, pos, old, cur) ; break ; 
				case STRING: stringIns.write(txnum, pageid, pos, old, cur) ; break ;
				case BYTES: bytesIns.write(txnum, pageid, pos, old, cur) ; break ;
				}
			}
			catch ( Exception e ) { 
				e.printStackTrace() ; 
				//System.out.println ( "System error while writinng log") ; 
			}
		}
		
		private static void writeCheckpoint () throws Exception {
			byte [] buff = new byte [ 4 ] ;
			long pos = file.getFilePointer() ; 
			file.seek ( 0 );
			//System.out.println ( "cheak" + file.length());
			ByteArray.writeInt ( buff, 0, (int)file.length() ) ;
			file.write( buff ) ;
			file.seek( pos ) ; 
		}
		
		public abstract void read () throws Exception ;
		public abstract void write ( int txnum, int pageid, int pos, Object old, Object cur) throws Exception ;
		public abstract void redo () ;
		public abstract void undo () ;  
}

